/**
 * 
 */
package com.agilegroup.crm.database;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.agilegroup.crm.model.CalendarStatus;

/**
 * @author hisham
 *
 */
public class CalendarDAO {
	
	private SQLiteDatabase db;
	private AgileSQLiteHelper dbHelper;
	
	public CalendarDAO(Context context) {
		dbHelper = new AgileSQLiteHelper(context);
	    db = dbHelper.getWritableDatabase();
	}
	public void close() {
	       db.close();
	   }
	public void createCalendar(String eventId,String isSync) {
	       ContentValues contentValues = new ContentValues();
	       contentValues.put("eventId", eventId);
	       contentValues.put("isSync", isSync);
	       db.insert("calendar", null, contentValues);
	   }
	
	public CalendarStatus getCalendar(String eventId) {
		String[] tableColumns = new String[] {"_id","eventId","isSync"};
		Cursor cursor = db.query("calendar", tableColumns, "eventId" + "=?",
				new String[] {eventId}, null, null, null, null);
		if(cursor!=null && cursor.getCount()>0){
			cursor.moveToFirst();
			   CalendarStatus calendarStatus = new CalendarStatus();
			   calendarStatus.setId(cursor.getInt(0));
			   calendarStatus.setEventId(cursor.getString(1));
	           calendarStatus.setIsSync(cursor.getString(2));
	           return calendarStatus;
		}
		else{
			return null;
		}
	}
	
	public boolean checkCalendarIsSynced(String eventId){
		 boolean isSynced=false;
		 CalendarStatus calendarStatus = getCalendar(eventId);
		 if(calendarStatus!=null){
			 if(calendarStatus.getEventId().equals(eventId)){
				 isSynced=true;
			 }
			 else{
					isSynced=false;
				}
		 }
		 else{
			 isSynced=false;
		 }
		 return isSynced;
	 }
	
	public List<CalendarStatus> getEvents(){
		 List<CalendarStatus> calendarList = new ArrayList<CalendarStatus>();
		 
		 String[] tableColumns = new String[] {"_id","eventId","isSync"};
		 
		 Cursor cursor = db.query("calendar", tableColumns, null, null, null, null, null);
	     cursor.moveToFirst();
	     
	     while (!cursor.isAfterLast()) {
	    	   CalendarStatus calendarStatus = new CalendarStatus();
	           // Take values from the DB
	    	   calendarStatus.setId(cursor.getInt(0));
	    	   calendarStatus.setEventId(cursor.getString(1));
	    	   calendarStatus.setIsSync(cursor.getString(2));
	 
	           // Add to the DB
	    	   calendarList.add(calendarStatus);
	 
	           // Move to the next result
	           cursor.moveToNext();
	       }
	 
	       return calendarList;
	 }
}
